package com.xiongjie.transaction;

import io.vertx.pgclient.PgConnectOptions;
import io.vertx.pgclient.PgPool;
import io.vertx.sqlclient.PoolOptions;
import io.vertx.sqlclient.Transaction;

/**
 * 事务模版，用于执行sql的事务处理
 */
public class TransactionDemo {

    //准备操作：启动postgres数据库，在数据库postgres中创建user表

    /**
     * 准备操作：启动postgres数据库，在数据库postgres中创建user表
     * create table userInfo(
     *      name text
     * )
     *
     * @param args
     */
    public static void main(String[] args) {
        PgConnectOptions connectOptions = new PgConnectOptions()
                .setPort(5432)
                .setHost("localhost")
                .setDatabase("postgres")
                .setUser("postgres")
                .setPassword("postgres");
        PoolOptions poolOptions = new PoolOptions()
                .setMaxSize(5);

        //连接池对数据库进行操作，也可以和vertx组合使用
        PgPool pool = PgPool.pool(connectOptions, poolOptions);

        pool.begin(begin -> {
            if (begin.succeeded()) {
                Transaction tx = begin.result();
                System.out.println("启动事务");

                tx.query("INSERT INTO userInfo (name) VALUES ('hexingjie')", ar2 -> {
                    tx.commit(v -> {
                        if (v.succeeded()) {
                            System.out.println("transaction succeeded");
                        } else {
                            System.out.println("transaction failed");
                        }
                        pool.close();
                    });
                });
            }
        });
    }
}
